/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */

/**
 * 所有需要对schema校验报错信息进行定制化修改的方法，统一管理
 */
import { HvigorLogger } from '@ohos/hvigor';

import { ConfigJson } from '../../options/configure/config-json-options.js';
import { ModuleJson } from '../../options/configure/module-json-options.js';

import { ErrorInfo } from './validate-util.js';
import ConfigOptObj = ConfigJson.ConfigOptObj;
import ModuleOptObj = ModuleJson.ModuleOptObj;

const _log = HvigorLogger.getLogger('ValidateErrorHandlers');

/**
 * 判断config.json/module.json5中deviceTypes是否存在phone，提示warning，构建不失败
 * 适用schema校验：config.json，module.json5
 * @param {ErrorInfo[]} errorInfos
 * @param {object} checkedFile
 */
export function removeLegacyPhoneSupport(errorInfos: ErrorInfo[], checkedFile?: object) {
  let needLogWarn = false;
  const moduleDeviceTypes = (checkedFile as ModuleOptObj).module?.deviceTypes;
  const configDeviceTypes = (checkedFile as ConfigOptObj).module?.deviceType;
  const deviceTypes = moduleDeviceTypes === undefined ? configDeviceTypes : moduleDeviceTypes;
  if (!Array.isArray(deviceTypes)) {
    return errorInfos;
  }
  errorInfos = errorInfos.filter((errorInfo) => {
    const instancePath = errorInfo.instancePath;
    const lastIndex = instancePath.lastIndexOf('[');
    const indexStr = instancePath.substring(lastIndex + 1);
    const indexNum = parseInt(indexStr);

    if (instancePath.indexOf('deviceType') !== -1 && deviceTypes.indexOf('phone') === indexNum) {
      needLogWarn = true;
      return false;
    }
    return true;
  });
  if (needLogWarn) {
    _log.warn(
      "Currently, the device type 'phone' is not supported in module.json5 " + "or config.json. You are advised to change the device type to 'default'.",
    );
  }
  return errorInfos;
}

/**
 * 对startWindow没有配置相关的问题，在solution中添加相应的跳转链接
 * 适用schema校验：module.json5
 * @param {ErrorInfo[]} errorInfos
 */
export function handleStartWindowErrors(errorInfos: ErrorInfo[]) {
  const keywords = ['startWindowIcon', 'startWindowBackground'];
  errorInfos.forEach((errorInfo) => {
    if (errorInfo.keyword.indexOf('required') !== -1 && keywords.includes(errorInfo.params['missingProperty'])) {
      errorInfo.solution = 'For help about startWindows, you can solve the problem with this FAQ.';
    }
  });
  return errorInfos;
}

/**
 * 对entryModules为空时报错的相关校验的补充说明
 * 适用schema校验：module级别build-profile.json5
 * @param {ErrorInfo[]} errorInfos
 */
export function handleEntryModulesErrors(errorInfos: ErrorInfo[]) {
  errorInfos.forEach((errorInfo) => {
    if (errorInfo.instancePath === 'entryModules' && errorInfo.keyword === 'minItems') {
      errorInfo.reason =
        'The entryModule field cannot be empty, because a feature module must ' +
        'have a corresponding entry module. This might happen when an entry module was removed.';
      errorInfo.solution = 'Add a dependent entry module to this feature module.';
    }
  });
  return errorInfos;
}
